import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCityStore = defineStore('city', () => {
  const cityList = ref([])

  // 从 localStorage 加载数据
  const loadFromStorage = () => {
    const savedCities = localStorage.getItem('savedCities')
    if (savedCities) {
      cityList.value = JSON.parse(savedCities)
    }
  }

  // 保存到 localStorage
  const saveToStorage = () => {
    localStorage.setItem('savedCities', JSON.stringify(cityList.value))
  }

  // 添加城市
  const addCity = (cityData) => {
    // 检查是否已存在
    if (!cityList.value.some(city => city.adcode === cityData.adcode)) {
      cityList.value.push(cityData)
      saveToStorage()
    }
  }

  // 删除城市
  const removeCity = (adcode) => {
    cityList.value = cityList.value.filter(city => city.adcode !== adcode)
    saveToStorage()
  }

  // 初始化时加载数据
  loadFromStorage()

  return {
    cityList,
    addCity,
    removeCity
  }
}) 